package cn.kgc.springmvc02.controller;

import cn.kgc.springmvc02.entity.ResponseResult;
import cn.kgc.springmvc02.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/7
 * @Description:
 */
@RequestMapping("res")
@Controller
//@ResponseBody   //   统一返回json格式数据
//@RestController
public class ResponseController {

    @RequestMapping("m1")
    public String method1() {

        return "user";  // 返回视图名  转发 视图解析器解析  /user.jsp
    }

    /*
     *ModelAndView
     * Model  数据模型
     * View  视图
     * */
    @RequestMapping("m2")
    public ModelAndView method2() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user");
        modelAndView.addObject("info", "modelValue");  // 经过视图解析器的解析 会将该数据存入request
        return modelAndView;
    }


    @RequestMapping("m3")
    public String method3(Model model) {
        model.addAttribute("info", "modelValue2");
        return "user";
    }

    /*
    *  json   ->  List<User>  -> json ->[{"username:"","age":20},{},{}]   JSON.parse()   ->  [{},{}]
    *  add  delete  update  - > {code:  ,msg: ,  data: ,  count:  }
    * */

    @RequestMapping("m4")
    @ResponseBody   // 将返回结果 以json格式进行返回
    public ResponseResult method4() {
        System.out.println("==========返回json格式数据=============");
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setCount(1000L);
        User user = new User();
        user.setName("tom");
        user.setNumber(10);
        responseResult.setData(user);
        responseResult.setMsg("查询成功");
        return responseResult;
    }


    @RequestMapping("m5")
    @ResponseBody   // 将返回结果 以json格式进行返回
    public Map method5(Integer id) {
        System.out.println("==========返回json格式数据=============");
        System.out.println("id = " + id);


        HashMap<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","ok");
        return map;
    }
}
